from web.models.user import User, Group
from web.views.api import route_api
from flask import request, jsonify
from application import app, db
import time
import os


@route_api.route('/upload/avatar', methods=['GET', 'POST'])
def upload_avatar():
    resp = {'code': 200, 'msg': '操作成功', 'data': {}}
    # 接收图片
    avatar = request.files.get('avatar')
    if not avatar:
        resp['code'] = -1
        resp['msg'] = '未检测到图片'
        return jsonify(resp)

    # 接收附加信息
    suffix = request.form.get('suffix')  # 文件格式
    upload_type = request.form.get('upload_type')  # 判断类型

    if upload_type == "user-avatar":
        user_id = request.form.get('user_id')  # 用户uid
        save_path = app.root_path + app.config['USER_AVATAR_SAVE_PATH']
        file_name = "{0}_{1}{2}".format(str(int(time.time())), user_id, suffix)
        result = save_img(save_path, file_name, avatar, resp)
        if result['status_code'] == -1:
            return jsonify(result['resp'])

        # 修改数据库
        with db.auto_commit():
            user_id = int(user_id)
            avatar_path = app.config['DOMAIN'] + app.config['USER_AVATAR_PATH'] + file_name  # 图片访问地址

            user = User.query.filter_by(uid=user_id).first()
            user.avatar = avatar_path
            db.session.add(user)

        return jsonify(resp)

    elif upload_type == "group-avatar":
        group_id = request.form.get('group_id')  # 群组gid
        save_path = app.root_path + app.config['GROUP_AVATAR_SAVE_PATH']
        file_name = "{0}_{1}{2}".format(str(int(time.time())), group_id, suffix)

        result = save_img(save_path, file_name, avatar, resp)
        if result['status_code'] == -1:
            return jsonify(result['resp'])

        # 修改数据库
        with db.auto_commit():
            group_id = int(group_id)
            avatar_path = app.config['DOMAIN'] + app.config['GROUP_AVATAR_PATH'] + file_name  # 图片访问地址

            group = Group.query.filter_by(gid=group_id, status=1).first()
            group.avatar = avatar_path
            db.session.add(group)

        return jsonify(resp)

    else:
        resp['code'] = -1
        resp['msg'] = 'No such upload_type'
        return jsonify(resp)


def save_img(path, name, data, resp):
    try:
        print("\n====================上传图片中======================\n")
        if not os.path.exists(path):
            os.mkdir(path)
        img_data = data.read()
        print(f"\n上传图片大小========================> {len(img_data) / 1024}KB\n")
        if len(img_data) > app.config['MAX_AVATAR_SIZE']:
            resp['code'] = -1
            resp['msg'] = '图片过大'
            return {'status_code': -1, 'resp': resp}

        with open(path + name, 'wb')as f:
            f.write(img_data)
        print("\n====================图片上传成功======================\n")
        return {'status_code': 1, 'resp': resp}

    except:
        resp['code'] = -1
        resp['msg'] = "图片上传失败"
        print("\n====================图片上传失败======================\n")
        return {'status_code': -1, 'resp': resp}
